<template>
  <div class="mapBox">
    <div id="map" v-if="mapShow"></div>
    <!-- 圈地按钮 -->
    <div class="btn">
      <el-button @click="openPolygonTool" :disabled="drawBtn"
        >开始绘制</el-button
      >
      <el-button @click="enableEdit()">编辑地块</el-button>
      <el-button @click="disableEdit()">结束编辑</el-button>
      <el-button type="primary" @click="delPolygon()">删除圈地</el-button>
    </div>
    <div></div>
    <!-- 搜索框 -->
    <div class="left-top">
      <el-input
        v-model="input"
        placeholder="请输入关键词搜索"
        class="address-search"
        @input="searchWithName"
      >
        <el-button size="mini" @click="addressList = [],input = null" slot="append"
          >确认选中</el-button
        >
      </el-input>
      <div class="address-list" v-show="addressList && addressList.length">
        <div
          v-for="(item, index) in addressList"
          :key="index"
          @click="selectOneAddr(item.address + item.name)"
        >
          <div>{{ item.address }}</div>
          <div>{{ item.name }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      map: {},
      T: '',
      handler: null, // 圈地用的
      polygonTool: null, // 控件
      polygon: null, // 面
      currentPolygon: '',
      landData: [],
      addressList: [], // 搜索框
      input: '',
      drawBtn: false,
      drawData: {
        // landInfo: null
      },
      geoCenter: null,
      geocode: null,
      geoColor: '#19b560,#ccc',
      mapShow: true,
      setTips: '<div style="width:10vw;height:2vw;background: rgba(25, 181, 96);padding:0.2vw;margin:-0.4vw 5vw 1vw -5vw;border-radius: 8px;position: absolute;top: 50%;left:-50%;">点击继续绘制，双击结束绘制</div></div>'// 绘制时显示的标签
    }
  },
  props: {
    landList: {
      type: Array
    }
  },
  watch: {
    // 搜索框
    input (val) {
      if (!val) {
        this.addressList = []
        // 用来清空删除太快时候出现列表的bug
        setTimeout(() => {
          this.addressList = []
        }, 3000)
      }
    }
  },
  mounted () {
    setTimeout(() => {
      this.load()
    }, 10)
  },
  methods: {
    load () {
      const init = new Promise((resolve, reject) => {
        if (window.T) {
          console.log('地图初始化成功')
          resolve(window.T)
        }
      })
      init.then((T) => {
        this.T = T
        this.map = new T.Map('map')
        this.map.centerAndZoom(new T.LngLat(108.17871, 35.60372), 5)
        console.log(this.landList, 'landList')
        // 合并所有经纬度调用setViewport在地图上显示所有圈地
        if (this.geoCenter === null && this.landList !== []) {
          let MapArray = []
          for (let i = 0; i < this.landList.length; i++) {
            const geoArray = JSON.parse(this.landList[i].geoInfo)
            MapArray = [...MapArray, ...geoArray]
          }
          this.map.setViewport(MapArray)
        } else if (this.landData !== []) {
          this.map.setViewport(this.landData)
        }

        // 双重for循环遍历所有的地块数据进行渲染
        for (let j = 0; j < this.landList.length; j++) {
          const geoObj = {}
          geoObj.geoInfo = JSON.parse(this.landList[j].geoInfo) // 经纬度
          geoObj.landName = this.landList[j].landName // 地块名称
          geoObj.landArea = this.landList[j].landArea // 地块名称

          const points = []
          for (let i = 0; i < geoObj.geoInfo.length; i++) {
            points.push(
              new T.LngLat(geoObj.geoInfo[i].lng, geoObj.geoInfo[i].lat)
            )
          }
          // 创建面对象
          this.polygon = new T.Polygon(points, {
            color: 'blue',
            weight: 3,
            opacity: 0.5,
            fillColor: '#FFFFFF',
            fillOpacity: 0.5,
            test: `<p>名称：${geoObj.landName}</p><p>面积：${geoObj.landArea}亩</p>`
          })
          // 添加点击事件
          this.polygon.addEventListener('click', this.getinfo)

          // 向地图上添加面
          this.map.addOverLay(this.polygon)
        }

        // 添加刚绘制的面
        const points = []
        for (let i = 0; i < this.landData.length; i++) {
          points.push(new T.LngLat(this.landData[i].lng, this.landData[i].lat))
        }
        // 创建面对象
        const color = this.geoColor.split(',').map(color => color.trim())
        this.polygon = new T.Polygon(points, {
          color: color[0], // 线
          weight: 3,
          opacity: 0.5,
          fillColor: color[1], // 面
          fillOpacity: 0.5
          // test: '<p>名称：梅林村稻田1区</p><p>面积：295亩</p>'
        })
        // 向地图上添加面
        this.map.addOverLay(this.polygon)
        // 地图图层
        const ctrl = new T.Control.MapType([

          {
            title: '卫星',
            icon: 'http://api.tianditu.gov.cn/v4.0/image/map/maptype/satellite.png',
            layer: window.TMAP_HYBRID_MAP
          }
          // {
          //   title: '地图',
          //   icon: 'http://api.tianditu.gov.cn/v4.0/image/map/maptype/vector.png', // 地图控件上所要显示的图层图标（默认图标大小80x80）
          //   layer: window.TMAP_NORMAL_MAP
          // }
        ])
        this.map.addControl(ctrl)
      })
    },
    getinfo (e) {
      // console.log(e)
      const T = this.T
      const that = this
      const p = e.target
      const lnglat = new T.LngLat(p.getCenter().lng, p.getCenter().lat) // 获取点击多边形中心经纬度
      const infoWin = new T.InfoWindow() // 创建信息窗口对象
      const Content = e.target.options.test // 设置信息窗口要显示的内容，此处可使用html代码;现在显示的就是之前在polygon实例中添加的数据
      infoWin.setContent(Content) // 信息窗口加入信息
      infoWin.setOffset(new T.Point(0, -30)) // 设置信息窗口边距，第一个决定X方向，第二个决定Y方向
      infoWin.setLngLat(lnglat) // 设置信息窗口位置
      that.map.addOverLay(infoWin) // 向地图上添加信息窗口
    },
    // 绘图事件
    openPolygonTool () {
      const T = this.T
      const config = {
        color: 'red',
        weight: 3,
        opacity: 0.5,
        fillColor: '#FFFFFF00',
        fillOpacity: 0
      }
      if (this.handler) this.handler.close()
      this.handler = new T.PolygonTool(this.map, config)
      this.handler.open()
      this.handler.setTips(this.setTips)
      // 圈地绘制
      this.handler.addEventListener('draw', this.getDraw)
      this.handler.addEventListener('addpoint', this.getAddPoint)
    },
    getAddPoint (e) {
      this.setTips = '<div style="width:10vw;height:2vw;background: rgba(25, 181, 96);padding:0.2vw;margin:-0.4vw 5vw 1vw -5vw;border-radius: 8px;position: absolute;top: 50%;left:-50%;">点击继续绘制，双击最后点位结束绘制</div></div>'
      console.log(e.currentLnglats, '绘画中')
    },
    // 绘制完成事件
    getDraw (e) {
      console.log(e, '画完了')
      this.landData = e.currentLnglats // 圈出地块经纬度 绘制后页面回显
      this.geoCenter = e.target.Eo // 中心点
      // 解决重新加载后地图无法拖动地图问题
      this.mapShow = false
      setTimeout(() => {
        this.mapShow = true
      }, 10)
      setTimeout(() => {
        this.load()
      }, 20)

      // 定位逆解析
      const T = this.T
      this.geocode = new T.Geocoder()
      // this.drawData = { ...this.drawData, ...e }
      this.drawData = e
      this.geocode.getLocation(this.geoCenter, this.searchResult)
      setTimeout(() => {
        this.$emit('areaData', this.drawData)// 子传父
      }, 300)
      this.drawBtn = true
    },
    // 逆解析
    searchResult (result) {
      this.drawData.landInfo = result.formatted_address
    },
    // 删除圈地
    delPolygon () {
      this.map.clearOverLays()//
      this.drawBtn = false
      this.drawData = { landInfo: null }
      // 清空数据，重新加载地图
      this.landData = {}
      this.geoCenter = null
      this.mapShow = false
      setTimeout(() => {
        this.mapShow = true
      }, 10)
      setTimeout(() => {
        this.load()
      }, 100)
      this.$emit('areaData', this.drawData)// 子传父
    },
    // 编辑面
    enableEdit () {
      // console.log(this.polygon, '开始编辑')
      this.polygon.enableEdit()
    },
    // 结束编辑面
    disableEdit () {
      this.polygon.disableEdit()
      this.drawData.currentLnglats = this.polygon.ht[0]// 新经纬度
      this.$emit('areaData', this.drawData)
    },
    // --------------------------------
    // 搜索
    confirm () {
      if (this.lng && this.lat && this.address) {
        this.$emit('closeMapaddressDialog', false)
      } else {
        this.$message.warning('鼠标点选或搜索选中地址后再进行确认')
      }
    },
    // 搜索 天地图LocalSearch
    searchWithName (val) {
      if (val) {
        const that = this
        const config = {
          pageCapacity: 10, // 每页显示的数量
          onSearchComplete: localSearchResult // 接收数据的回调函数
        }
        // 创建搜索对象
        const T = this.T
        const localsearch = new T.LocalSearch(that.map, config)
        localsearch.search(that.input, 1)
        // console.log(localsearch)
        function localSearchResult (result) {
          // console.log(result.lineData)
          // 清空地图及搜索列表
          // clearAll()
          // 解析建议词信息
          // result.getPois()
          // console.log(result)
          suggests(result.getPois())
        }
        // 解析建议词信息
        function suggests (obj) {
          if (obj && obj.length) {
            console.log(obj, 'suggests')
            that.addressList = obj
            console.log(that.addressList)
          }
        }
        // 清空地图及搜索列表
        // function clearAll () {
        //   that.map.clearOverLays()
        // }
      } else {
        this.addressList = []
      }
    },
    // 点击搜索内容地图跳转
    selectOneAddr (val) {
      const that = this
      const T = this.T
      that.map.clearOverLays()
      // 创建对象
      const geocoder = new T.Geocoder()
      geocoder.getPoint(val, searchResult)
      function searchResult (result) {
        if (result.getStatus() === 0) {
          that.map.panTo(result.getLocationPoint(), 16)
          // 创建标注对象
          // const marker = new T.Marker(result.getLocationPoint())
          // 向地图上添加标注
          // const label = new T.Label({
          //   text: val,
          //   position: result.getLocationPoint(),
          //   offset: new T.Point(10, -20)
          // })
          // that.map.addOverLay(label)
          // that.map.addOverLay(marker)
          that.address = val
          that.$emit('setAddress', val)
          that.lng = result.getLocationPoint().lng
          that.lat = result.getLocationPoint().lat
          that.$emit('setPosition', [
            result.getLocationPoint().lng,
            result.getLocationPoint().lat
          ])
        } else {
          this.$message.warning('定位出错请重新选择')
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
#map {
  width: 76vw;
  height: 60vh;
}

.mapBox {
  position: relative;
}
.btn {
  position: absolute;
  bottom: 5%;
  right: 5%;
  z-index: 999;
}
#right-btn {
  visibility: hidden;
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: 999;
  background-color: #fff;
  cursor: pointer;
  border: 1px solid #dee1e6;
}

.right-item {
  margin: 4px;
  font-size: 12px;
}

.right-item:hover {
  color: #23aaf2;
}
::v-deep .tat-label1 {
  border: none !important;
  background-color: transparent !important;
}
</style>

<style lang="stylus" scoped>
.cur {
  cursor: pointer;
}

.map-address {
  height: 60vh;
}

#mapDiv {
  height: 100%;
  position: relative;
}

.left-top {
  position: absolute;
  left: 35px;
  top: 20px;
  display: flex;
  flex-direction: column;
}

.address-search {
  width: 20vw;
  z-index: 10000;
  margin-bottom: 20px;
}

.address-list {
  display: flex;
  flex-direction: column;
  z-index: 10000;
  background-color: #fff;
  padding: 10px;
  min-width: 18vw;
  border: 1px solid #DCDFE6;

  >div {
    display: flex;
    align-items: center;
    height: 30px;
    cursor: pointer;
    color: #409eff;

    &:hover {
      background-color: #eee;
    }
  }
}
</style>
